package main

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"tool/utils/sql"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/widget"
	"github.com/google/shlex"
)

// 服务启动
func (app *config) serviceStartup() func() {
	return func() {
		// w := app.New()
		w := fyne.CurrentApp().NewWindow("服务启动")

		list := sql.QueryServerStartList("select * from server_start order by id desc")
		addBtn := widget.NewButton("添加服务", func() {})
		addBtn.OnTapped = func() {
			// sql.QueryServerStartList("select * from server_start order by id desc")
			addServiceFunc := app.addServiceFunc("insert")
			addServiceFunc()
		}
		refreshBtn := widget.NewButton(" 刷新 ", func() {})
		cmdBtn := widget.NewButton(" cmd ", func() {})
		var refreshList func()

		listLayout := widget.NewList(
			func() int {
				return len(list)
			},
			func() fyne.CanvasObject {

				name := widget.NewLabel("服务名称")

				deleteBtn := widget.NewButton("删除", func() {})
				editBtn := widget.NewButton("修改", func() {})
				app.StartCommondBtn = widget.NewButton(" 启动 ", func() {})

				command := widget.NewLabel("command")

				return container.New(layout.NewVBoxLayout(), container.New(layout.NewHBoxLayout(), name, deleteBtn, editBtn, app.StartCommondBtn), container.New(layout.NewHBoxLayout(), command))
			},
			func(index widget.ListItemID, o fyne.CanvasObject) {
				objects := o.(*fyne.Container).Objects[0].(*fyne.Container).Objects
				objects1 := o.(*fyne.Container).Objects[1].(*fyne.Container).Objects

				objects[0].(*widget.Label).SetText(list[index].Name)
				objects1[0].(*widget.Label).SetText(list[index].Value)

				//删除
				objects[1].(*widget.Button).OnTapped = func() {

					cnf := dialog.NewConfirm("提示", "您是否要删除服务", func(response bool) {
						if response {
							sql.Delete("delete from server_start where id=?", strconv.Itoa(list[index].Id))
							// refreshList()
						}
					}, w)
					cnf.SetDismissText("取消")
					cnf.SetConfirmText("确认")
					cnf.Show()
				}

				//修改
				objects[2].(*widget.Button).OnTapped = func() {
					app.ServiceStart = ServiceStartClass{Id: strconv.Itoa(list[index].Id), Name: list[index].Name, Value: list[index].Value}
					addServiceFunc := app.addServiceFunc("edit") // 获取函数
					addServiceFunc()                             // 执行函数
				}

				objects[3].(*widget.Button).OnTapped = func() {
					commandArr := strings.Split(list[index].Value, ",")
					var err error
					var parts []string
					if app.StartCommondBtn.Text == " 启动 " {
						parts, err = shlex.Split(commandArr[0])
					} else if app.StartCommondBtn.Text == " 停止 " {
						parts, err = shlex.Split(commandArr[1])
					}
					if err != nil {
						fmt.Println("Error parsing command:", err)
						return
					}
					command := parts[0]
					args := parts[1:]

					cmd := exec.Command(command, args...)
					// 设置标准输出和错误
					cmd.Stdout = os.Stdout
					cmd.Stderr = os.Stderr
					// 执行命令
					err = cmd.Run()
					if err != nil {
						log.Fatalf("命令执行失败: %v", err)
					}

					fmt.Println("successfully.")
					if app.StartCommondBtn.Text == " 启动 " {
						app.StartCommondBtn.SetText(" 停止 ")
						app.StartCommondBtn.Refresh() // 强制刷新按钮
						toast("服务启动成功", w)
					} else if app.StartCommondBtn.Text == " 停止 " {
						app.StartCommondBtn.SetText(" 启动 ")
						app.StartCommondBtn.Refresh() // 强制刷新按钮
						toast("服务停止成功", w)
					}

				}

			},
		)

		refreshList = func() {
			list = sql.QueryServerStartList("select * from server_start order by id desc")
			// 刷新列表组件
			listLayout.Refresh()
		}
		refreshBtn.OnTapped = refreshList

		rowLayout_1 := container.New(layout.NewHBoxLayout(), addBtn, refreshBtn, cmdBtn)
		rowLayout_2 := container.New(layout.NewVBoxLayout(), rowLayout_1, widget.NewLabel(""))
		allLayout := container.NewBorder(rowLayout_2, nil, nil, nil, listLayout)
		w.SetContent(allLayout)

		w.SetFixedSize(true) // 设置固定大小，避免用户拖动改变大小

		// start 监听主窗口的关闭事件
		// 前提是必须设置主窗口
		w.SetOnClosed(func() {
			w.Close()
		})
		// end 监听主窗口的关闭事件

		// 设置窗口大小,
		w.Resize(fyne.NewSize(500, 400))
		w.CenterOnScreen()
		w.Show()
	}
}

// 添加服务
func (app *config) addServiceFunc(types string) func() {
	return func() {
		title := "添加服务"
		if types == "insert" {
			title = "添加服务"
		} else {
			title = "编辑服务"
		}
		w := fyne.CurrentApp().NewWindow(title)

		nameLabel := widget.NewLabel("服务名称")
		nameInput := widget.NewEntry()
		nameInput.SetPlaceHolder("请输入服务名称")
		rowLayout_1 := container.NewBorder(nil, nil, nameLabel, layout.NewSpacer(), nameInput)

		nameOrgPathLabel := widget.NewLabel("服务命令")
		nameOrgPathInput := widget.NewEntry()
		nameOrgPathInput.SetPlaceHolder("请输入服务命令")
		nameOrgPathInput.Wrapping = 2     // 开启自动换行
		nameOrgPathInput.MultiLine = true //多行输入
		rowLayout_2 := container.NewBorder(nil, nil, nameOrgPathLabel, layout.NewSpacer(), nameOrgPathInput)

		if types == "insert" {
			nameInput.SetText("")
			nameOrgPathInput.SetText("")
		} else {
			nameInput.SetText(app.ServiceStart.Name)
			nameOrgPathInput.SetText(app.ServiceStart.Value)
		}

		saveBtn := widget.NewButton("保存", func() {
			if types == "insert" {
				sql.Insert("insert into server_start (name,value) VALUES(?,?)", nameInput.Text, nameOrgPathInput.Text)
			} else {
				sql.Update("update server_start set name=?,value=? where id=?", nameInput.Text, nameOrgPathInput.Text, app.ServiceStart.Id)
			}
			w.Close()
		})

		allLayout := container.New(layout.NewVBoxLayout(), rowLayout_1, rowLayout_2, saveBtn)

		w.SetContent(allLayout)
		w.SetFixedSize(true) // 设置固定大小，避免用户拖动改变大小
		// start 监听主窗口的关闭事件
		// 前提是必须设置主窗口
		w.SetOnClosed(func() {
			w.Close()
		})
		// edn 监听主窗口的关闭事件

		// 设置窗口大小,
		w.Resize(fyne.NewSize(400, 200))
		w.CenterOnScreen()
		w.Show()
	}
}
func removeElement(slice []string, index int) []string {
	// 检查索引是否越界
	if index < 0 || index >= len(slice) {
		return slice
	}
	// 将索引位置之后的元素向前移动一位
	return append(slice[:index], slice[index+1:]...)
}
